<script setup lang="ts">
import { useToast } from "wot-design-uni";
import { listMock } from "./mock";
import blank from "@/static/images/blank.png";

const toast = useToast();

const props = defineProps<{
	fetchMehod;
	defaultParams;
	refresh: boolean;
}>();

const data = ref([]);

const state = ref<"loading" | "finished" | "error">("finished");

const params = reactive({
	pageNo: 1,
	pageSize: 10,
	...props.defaultParams,
});

const pageParams = reactive({
	loading: false,
	total: 0,
});

const requestData = async () => {
	pageParams.loading = true;
	toast.loading({ msg: "加载中", duration: 0 });

	try {
		const rs = await props.fetchMehod(params);
		// const rs = listMock[params.pageNo];

		if (rs.list && rs.list.length > 0) {
			const _d = data.value;
			_d.push(...rs.list);

			console.log(_d);

			data.value = _d;

			pageParams.total = rs.total;
		}
	} catch (error) {
		console.log(error);
	} finally {
		pageParams.loading = false;
		setTimeout(() => toast.close(), 500);
	}
};

const reload = () => {
	data.value = [];
	pageParams.loading = false;
	pageParams.total = 0;
	Object.assign(params, {
		pageNo: 1,
		pageSize: 10,
	});
	requestData();
}

onReachBottom(() => {
	if (params.pageSize * params.pageNo >= pageParams.total) {
		state.value = "finished";
		return;
	}
	params.pageNo = params.pageNo + 1;
	requestData();

	state.value = "loading";
});

onLoad(() => {
	requestData();
});

watch(
	() => props.defaultParams,
	(val) => {
		Object.assign(params, val);
		uni.pageScrollTo({ scrollTop: 0, duration: 0 });

		pageParams.total = 0;
		params.pageNo = 1;
		params.pageSize = 10;
		data.value = [];
		requestData();
	},
	{ deep: true },
);

defineExpose({
	reload
})
</script>

<template>
	<view class="container">
		<template v-if="data.length">
			<view v-for="item in data" :key="item" class="list-item">
				<slot name="listItem" :data="item"></slot>
			</view>
			<wd-loadmore :state="state" />
		</template>
		<template v-else>
			<view class="blank">
				<wd-img :src="blank" class="blank-img" />
				<view class="text">暂无数据</view>
			</view>
		</template>
	</view>

	<wd-toast></wd-toast>
</template>

<style lang="less" scoped>
.container {
	width: 100%;
	height: auto;
}

.blank {
	width: 80%;
	height: 500px;
	margin: 10px auto;
	padding-bottom: 50px;

	.blank-img {
		width: 100%;
		height: 100%;
	}

	.text {
		text-align: center;
		font-size: 35px;
		color: rgba(0, 0, 0, 0.45);
	}
}
</style>
